var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
let request = require('superagent');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// var history = require('connect-history-api-fallback');
var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// app.use(history());
app.use(express.static(path.join(__dirname, 'public')));
let HOST = 'http://api.douban.com/v2'
app.all('*', function (req, res, next) {
    if (!req.get('Origin')) return next()
    // use "*" here to accept any origin
    res.set('Access-Control-Allow-Origin', '*')
    res.set('Access-Control-Allow-Methods', 'GET')
    res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
    // res.set('Access-Control-Allow-Max-Age', 3600);
    if (req.method === 'OPTIONS') return res.send(200)
    next()
})
let requestList =
    [
        '/movie/:type',
        '/movie/subject/:id',
        '/movie/subject/:id/reviews',
        '/movie/subject/:id/comments',
        '/movie/celebrity/:id'
    ]
requestList.forEach(requestItem => {
    app.get(requestItem, function (req, res) {
        let sreq = request.get(HOST + req.originalUrl)
        sreq.pipe(res)
        sreq.on('end', function (error, res) {
            console.log(`>>> fetch ${requestItem} succeed`)
        })
    })
})

app.use('/', indexRouter);
app.use('/users', usersRouter);

module.exports = app;
